package com.boot.common.utils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Cheng JiYe
 * @description: Map转换工具类
 * @date 2020/10/2 1:41
 */
public class ReturnMapUtil implements Serializable {
  private static final long serialVersionUID = 56231324L;

  /**
   * 把实体类转换成Map
   *
   * @param object
   * @return
   * @throws Exception
   */
  public static Map<String, Object> transformationMap(Object object) {
    if (object == null) {
      return null;
    }
    Map<String, Object> map = new HashMap<>(100);
    Class cla = object.getClass();
    Field[] fields = cla.getDeclaredFields();
    for (Field field : fields) {
      if ("serialVersionUID".equals(field.getName())) {
        continue;
      }
      Method method = null;
      try {
        method =
            cla.getMethod(
                "get"
                    + (field.getName().substring(0, 1)).toUpperCase()
                    + field.getName().substring(1));
        Object value = method.invoke(object);
        if (value != null) {
          map.put(field.getName(), value);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return map;
  }

  /**
   * 实体类集合转成Map集合
   *
   * @param object
   * @return
   * @throws Exception
   */
  public static List<Map<String, Object>> transformationListMap(List object) {
    List<Map<String, Object>> list = new ArrayList<>(object.size());
    for (Object o : object) {
      list.add(transformationMap(o));
    }
    return list;
  }
}
